//
//  DYCMeViewController.m
//  DYCBaisi
//
//  Created by Yachao on 17/6/29.
//  Copyright © 2017年 Yachao. All rights reserved.
//

#import "DYCMeViewController.h"
#import "DYCSettingViewController.h"
#import "DYCSquareItem.h"
#import "DYCSquareCell.h"
#import <SafariServices/SafariServices.h>
#import "DYCWebViewController.h"
/*
 搭建基本结构 -> 设置底部条 -> 设置顶部条 -> 设置顶部条标题字体 -> 处理导航控制器业务逻辑(跳转)
 
 */
static NSString * const ID = @"cell";
static NSInteger const cols = 4;
static CGFloat const margin = 1;
#define itemWH (DYCScreenW - (cols - 1) * margin) / cols

@interface DYCMeViewController ()<UICollectionViewDataSource, UICollectionViewDelegate, SFSafariViewControllerDelegate>

@property (nonatomic, strong) NSMutableArray *squareItems;
@property (nonatomic, weak) UICollectionView *collectionView;

@end


@implementation DYCMeViewController

- (void)viewDidLoad {
    [super viewDidLoad];
        
    // 设置导航条
    [self setupNavBar];
    
    // 设置tableView底部视图
    [self setupFootView];
    
    // 展示方块内容 -> 请求数据(查看接口文档)
    [self loadData];
    
    /*
     跳转细节:
     1.collectionView高度重新计算 =>  collectionView高度需要根据内容去计算 => 有数据了 需要在计算下高度
     2.collectionView不需要滚动
     */
    
    // 处理cell间距,默认tableView分组样式,有额外头部和尾部间距
    self.tableView.sectionHeaderHeight = 0;
    self.tableView.sectionFooterHeight = 10;
    //边距
    self.tableView.contentInset = UIEdgeInsetsMake(-25, 0, 0, 0);
}

/*
//下面两个方法是为了确定头部距离顶部的距离
// 打印celly值
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
    
    NSLog(@"%@",NSStringFromCGRect(cell.frame));
    
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    
    NSLog(@"%@",NSStringFromUIEdgeInsets(self.tableView.contentInset));
}
*/
#pragma mark - 请求数据
- (void)loadData{
    // 1.创建请求会话管理者
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    
    // 2.拼接请求参数
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    parameters[@"a"] = @"square";
    parameters[@"c"] = @"topic";
    
    // 3.发送请求
    [manager GET:BasicApi parameters:parameters progress:^(NSProgress * _Nonnull downloadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        //[responseObject writeToFile:@"/Users/ChaoMac/Desktop/DYCBaisi/DYCBaisi/Classes/Me(我)/square.plist" atomically:YES];
        NSArray *dictArr = responseObject[@"square_list"];
        // 字典数组转换成模型数组
        _squareItems = [DYCSquareItem mj_objectArrayWithKeyValuesArray:dictArr];
        
        // 处理数据
        [self resloveData];
        
        // 设置collectionView 计算collectionView高度 = rows * itemWH
        // Rows = (count - 1) / cols + 1     3 cols=4
        NSInteger count = _squareItems.count;
        NSInteger rows = (count - 1) / cols + 1;
        // 设置collectioView高度
        self.collectionView.dyc_height = rows * itemWH;
        
        // 设置tableView滚动范围:自己计算
        self.tableView.tableFooterView = self.collectionView;
        
        // 刷新表格
        [self.collectionView reloadData];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        DYCLog(@"error == %@", error);
    }];
    
}

#pragma mark - 处理请求完成数据
- (void)resloveData{
    // 判断下缺几个
    // 3 % 4 = 3 cols - 3 = 1
    // 5 % 4 = 1 cols - 1 = 3
    
    NSInteger count = self.squareItems.count;
    NSInteger exter = count % cols;
    if (exter) {
        exter = cols - exter;
        for (int i = 0; i < exter; i++) {
            DYCSquareItem *item = [[DYCSquareItem alloc] init];
            [self.squareItems addObject:item];
        }
    }
}

#pragma mark - 设置tableView底部视图
- (void)setupFootView{
    /*
     1.初始化要设置流水布局
     2.cell必须要注册
     3.cell必须自定义
     */
    
    // 创建布局
    UICollectionViewFlowLayout  *layout = [[UICollectionViewFlowLayout alloc] init];
    
    // 设置cell尺寸
    //NSInteger cols = 4;//每行有几个item
    //CGFloat margin = 1;//每个item之间的间距
    //CGFloat itemWH = (DYCScreenW - (cols - 1) * margin) / cols;//每个item的宽度和高度
    
    
    //设置单元格大小
    layout.itemSize = CGSizeMake(itemWH, itemWH);
    //设置单元格的最小水平间距
    layout.minimumInteritemSpacing = margin;
    //设置最小行间距
    layout.minimumLineSpacing = margin;
    
    // 创建UICollectionView
    UICollectionView *collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 0, 0, 300) collectionViewLayout:layout];
    _collectionView = collectionView;
    _collectionView.backgroundColor = self.tableView.backgroundColor;
    self.tableView.tableFooterView = collectionView;
    collectionView.dataSource = self;
    collectionView.delegate = self;
    collectionView.scrollEnabled = NO;
    
    // 注册cell
    [collectionView registerNib:[UINib nibWithNibName:@"DYCSquareCell" bundle:nil] forCellWithReuseIdentifier:ID];
//    [collectionView registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:ID];
}

#pragma mark - UICollectionViewDelegate
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    
    // 跳转界面 push 展示网页
    /*
     1.Safari openURL :自带很多功能(进度条,刷新,前进,倒退等等功能),必须要跳出当前应用
     2.UIWebView (没有功能) ,在当前应用打开网页,并且有safari,自己实现,UIWebView不能实现进度条
     3.SFSafariViewController:专门用来展示网页 需求:即想要在当前应用展示网页,又想要safari功能 iOS9才能使用
        3.1 导入#import <SafariServices/SafariServices.h>
     4.WKWebView:iOS8 (UIWebView升级版本,添加功能 1.监听进度 2.缓存)
        4.1 导入#import <WebKit/WebKit.h>
     */
    
    
    
    DYCSquareItem *item = self.squareItems[indexPath.row];
    if (![item.url containsString:@"http"]) {
        return;
    }
    
    /*
    NSURL *url = [NSURL URLWithString:item.url];
    // SFSafariViewController使用Modal
    SFSafariViewController *safariVc = [[SFSafariViewController alloc] initWithURL:url];
    safariVc.delegate = self;
    //[self presentViewController:safariVc animated:YES completion:nil];
    self.navigationController.navigationBarHidden = YES;
    [self.navigationController pushViewController:safariVc animated:YES];
    */
    
    // 创建网页控制器
    DYCWebViewController *webVC = [[DYCWebViewController alloc] init];
    webVC.url = [NSURL URLWithString:item.url];
    [self.navigationController pushViewController:webVC animated:YES];
    
}

#pragma mark - SFSafariViewControllerDelegate
- (void)safariViewControllerDidFinish:(SFSafariViewController *)controller{
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark - UICollectionViewDataSource
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return self.squareItems.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    // 从缓存池取
    DYCSquareCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:ID forIndexPath:indexPath];
    cell.item = _squareItems[indexPath.row];
    return cell;
}
#pragma mark - 设置导航条
- (void)setupNavBar
{
    // 右边按钮
    // 把UIButton包装成UIBarButtonItem.就导致按钮点击区域扩大
    //设置
    UIBarButtonItem *settingItem = [UIBarButtonItem itemWithimage:[UIImage imageNamed:@"mine-setting-iconN"] highImage:[UIImage imageNamed:@"mine-setting-icon-clickN"] target:self action:@selector(setting)];
    
    //夜间模式
    UIBarButtonItem *nightItem = [UIBarButtonItem itemWithimage:[UIImage imageNamed:@"mine-moon-icon"] selImage:[UIImage imageNamed:@"mine-moon-icon-click"] target:self action:@selector(night:)];
    self.navigationItem.rightBarButtonItems = @[settingItem, nightItem];
    
    // titleView
    self.navigationItem.title = @"我的";
}

- (void)night:(UIButton *)button
{
    button.selected = !button.selected;
    
}

- (void)setting
{
    // 跳转到设置界面
    DYCSettingViewController *settingVC = [[DYCSettingViewController alloc] init];
    // 必须要在跳转之前设置
    settingVC.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:settingVC animated:YES];
    /*
     1.底部条没有隐藏
     2.处理返回按钮样式
     
     */
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end
